package com.ltx.vizflowservice.handler;


import com.alibaba.fastjson2.JSON;
import com.ltx.vizflowservice.common.convention.errorcode.BaseErrorCode;
import com.ltx.vizflowservice.common.convention.result.Results;
import com.ltx.vizflowservice.domain.entity.User;
import com.ltx.vizflowservice.service.UserService;
import com.ltx.vizflowservice.util.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@AllArgsConstructor
public class TokenInterceptor implements HandlerInterceptor {

    private UserService userService;

    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");

        token = token.replace("Bearer ", "");

        String s = redisTemplate.opsForValue().get(token);

        // 返回信息用户登录token已过期
        if (!StringUtils.hasLength(s)){
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            try (PrintWriter out = response.getWriter()) {
                out.print(JSON.toJSONString(Results.failure(BaseErrorCode.USER_LOGIN_TIMEOUT_ERROR))); // 写入JSON字符串
            }
        }

        // 每次访问重启设置过期时间
        redisTemplate.expire(token, 7, TimeUnit.DAYS);

        User user = userService.getById(s);

        // 将用户信息存储到ThreadLocal中
        UserContext.setUser(user);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后，从ThreadLocal中移除用户信息
        UserContext.removeUser();
    }
}